package git.soulbgm.utils;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * ZIP工具类
 *
 * @author SoulBGM
 * @date 2022-12-30
 */
public class ZipUtil {

    private static final LogHelper LOG = new LogHelper(IoUtil.class);

    /**
     * 支持单文件或多层文件夹的压缩
     *
     * @param srcPath    src路径
     * @param targetPath 目标路径
     */
    public static void zipFile(String srcPath, String targetPath) throws IOException {
        int length;
        File file = new File(srcPath);
        List<File> filesToArchive;
        if (file.isDirectory()) {
            filesToArchive = getAllFile(new File(srcPath));
            length = srcPath.length();
        } else {
            filesToArchive = Collections.singletonList(file);
            length = file.getParent().length() + 1;
        }
        try (ArchiveOutputStream o = new ZipArchiveOutputStream(new File(targetPath))) {
            for (File f : filesToArchive) {
                ArchiveEntry entry = o.createArchiveEntry(f, f.getPath().substring(length + 1));
                o.putArchiveEntry(entry);
                if (f.isFile()) {
                    try (InputStream i = Files.newInputStream(f.toPath())) {
                        IOUtils.copy(i, o);
                    }
                }
                o.closeArchiveEntry();
            }
        }
    }

    /**
     * 获取所有文件
     *
     * @param dirFile 目录文件
     * @return {@link List}<{@link File}>
     */
    public static List<File> getAllFile(File dirFile) {
        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0) {
            return Collections.emptyList();
        }
        List<File> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            if (childFile.isFile()) {
                files.add(childFile);
            } else {
                files.add(childFile);
                List<File> cFiles = getAllFile(childFile);
                if (cFiles.isEmpty()) {
                    continue;
                }
                files.addAll(cFiles);
            }
        }
        return files;
    }


    /**
     * 解压zip包至目标目录下，若目录不存在会自动新建；
     * utf-8编码的zip文件中存在gbk编码的文件和文件夹，解码会有乱码
     * 文件夹名称存在中文的，新建文件夹会失败，采取跳过的策略
     * 若存在中文命名的文件会抛出异常，采取跳过的策略
     *
     * @param inputStream 输入的文件流
     * @param destDir     解压的目标地址
     */
    public static void unzip(InputStream inputStream, String destDir) {
        ArchiveEntry zipEntry;
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
             ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(bufferedInputStream)) {
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                File file = new File(destDir, zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    boolean mkdirs = file.mkdirs();
                    if (!mkdirs) {
                        LOG.info("make dir fails, dir exists Chinese");
                    }
                } else {
                    try (FileOutputStream outPut = openOutputStream(file);
                         BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outPut)) {
                        IOUtils.copy(zipInputStream, bufferedOutputStream, 8192);
                    } catch (IOException e) {
                        LOG.info("file exists Chinese");
                    }
                }
            }
        } catch (IOException e) {
            LOG.info("have an IOException", e);
            throw new RuntimeException("解压失败", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                LOG.info("failed to close the input stream");
            }
        }
    }

    /**
     * 打开输出流
     *
     * @param file 文件
     * @return {@link FileOutputStream}
     * @throws IOException ioexception
     */
    public static FileOutputStream openOutputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }

            if (!file.canWrite()) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null && !parent.exists() && !parent.mkdirs()) {
                throw new IOException("File '" + file + "' could not be created");
            }
        }

        return new FileOutputStream(file);
    }

}
